package pers.cz.postgirl.core.async;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lmax.disruptor.EventHandler;
import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.postgirl.config.SystemEnum;
import pers.cz.postgirl.core.Spy;
import pers.cz.postgirl.core.store.Store;
import pers.cz.postgirl.core.enums.StoreEnum;
import pers.cz.postgirl.util.JefLog;
import pers.cz.postgirl.util.StringUtils;

import java.util.List;

/**
 * @program: postgirl-client
 * @description: SpyEventConsumer 事件消费者，用于处理队列中的spy,将spy保存到store
 * @author: Cheng Zhi
 * @create: 2023-05-30 15:10
 **/
public class SpyEventConsumer implements EventHandler<SpyEvent> {

    private JefLog jefLog = new JefLog(SpyEventProducer.class);

    @Override
    public void onEvent(SpyEvent spyEvent, long l, boolean b) throws Exception {
        try {
            Spy merged = spyEvent.getValue();
            String storeStrategy = JefConfiguration.get(SystemEnum.CLIENT_STORE_STRATEGY, "memory");
            jefLog.debug("展示当前存储策略：" + storeStrategy);
            Store store = StoreEnum.getStoreInstance(storeStrategy);
            long caseId = merged.getCaseId();
            String md5 = StringUtils.getMD5ByParam(merged.getParamValueList());
            // 注意这里前面的使用中横杠，最后一个使用下横杠
            String key = caseId + "-" + merged.getClzName() + "-" + merged.getMethodName()  + "-" + merged.getParamTypeList().size() + "_" + md5;
            // showParam(merged.getParamTypeList());
            store.set(key, merged);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showParam(List<Object> val) {
        try {
            jefLog.debug("====入参明细：" + JSON.toJSONString(val, SerializerFeature.IgnoreNonFieldGetter));
        } catch (Exception e) {
            jefLog.debug("展示入参明细出错==");
            e.printStackTrace();
        }
    }
}
